import os
import sys
import json
import subprocess
import re
import git
from git import Repo
from tqdm import tqdm
# 注意:需要先安装 GitPython
# pip install GitPython tqdm

# git进程
class GitProgress(git.remote.RemoteProgress):
    _tq = None
    def __init__(self, tq):
        self._tq = tq
        super().__init__()

    def update(self, op_code, cur_count, max_count=None, message=''):
        if len(message) != 0:
            self._tq.update(100 - self._tq.n)
            self._tq.set_description(message)

# 创建文件夹
def create_dir(dir_path):
    if not os.path.exists(dir_path):
        os.makedirs(dir_path)
        return True
    else:
        print(f'目录已存在:{dir_path}, 无需创建及拉取代码')
        return False

# 获取git扫描目录的配置文件
def get_gitscan_json(filename):
    data = None
    with open(filename, 'r') as f:
        # 读取文件内容
        data = json.load(f)
        return data
    return data

# 执行git克隆命令
def git_clone(repo_url, target_dir):
    with tqdm(total=100, desc='Cloning', unit='% ', unit_scale=True) as tq:
        repo = git.Repo.clone_from(repo_url, target_dir, progress=GitProgress(tq))

# 解析配置json自动创建目录并拉取代码
def get_gitscan_clones(json_config, deep):
    git_projects = get_gitscan_json(json_config)
    for project in git_projects:
        # 使用os.path.dirname截取目录路径
        repo_url = project["repo_url"]
        target_dir = os.path.dirname(project["path"])
        pattern = "/"  # 匹配一个或多个数字
        matches = re.findall(pattern, target_dir)
        if len(matches) == deep:
            # 创建文件夹, 并自动执行git clone命令
            if create_dir(target_dir) == True:
                git_clone(repo_url, target_dir)
                pass
            pass

# 读取文件,并使用for循环遍历解析后的数组
path_deep = 3
gitscan_json = 'gitscan.json'
get_gitscan_clones(gitscan_json, path_deep)
